package com.seele.tigerwallet.api;


import android.text.TextUtils;
import android.util.Log;

import com.seele.base.utils.LogUtils;
import com.seele.tigerwallet.BuildConfig;
import com.seele.tigerwallet.model.UserInfo;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.SignatureException;
import java.security.cert.CertificateException;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;




public class APIModule {

    public static final long HTTP_CONNECT_TIMEOUT = 15L;//链接时间
    public static final long HTTP_READ_TIMEOUT = 15L;//读取时间
    public static final long HTTP_WRITE_TIMEOUT = 15L;


    private static final String TAG = APIModule.class.getSimpleName();
    private static OkHttpClient mOkHttpClient;

    private static Map<String, String> mParameter;


    private static Retrofit mRetrofit;

    private static Object mLock = new Object();
    private static String FRONT_URL;

    private Retrofit mFileRetrofit;

    public static String BASE_URL;


    public static String BASE_TEST_TW5 = "https://tw5.niren.org/wallet/";//开发

    public static String BASE_TEST_TW3 = "https://tw3.niren.org/wallet/";//正式

    public static String BASE_TEST_TW1 = "https://tw1.niren.org/wallet/";//测试


    public static String API_URL;

    public static boolean isFlag;

    private String fileUrl;
    private static String mSession;
    private static boolean sessioneEror;

    public static void setSession(String session) {
        mSession = session;
        isFlag = true;
//        isFlag=true;
        if (!TextUtils.isEmpty(session) && null != mParameter) {
            mParameter.put("session", session);
        } else {
            Log.i(TAG, "session is null");
        }

    }

    public static void setSession2(String session) {
        mSession = session;
        isFlag = true;

        if (!TextUtils.isEmpty(session) && null != mParameter) {
            mParameter.put("session", session);
        } else {
            Log.i(TAG, "session is null");
        }

    }

    public static void setToken(String token) {
        if (!TextUtils.isEmpty(token) && null != mParameter) {
            mParameter.put("token", token);
        }
    }

    public static void setApiUrl(String apiUrl) {
        API_URL = getUrl(apiUrl);
    }

    public static String getUrl(String url) {

        return "https://" + url + "/wallet/";
    }


    public static String getTokeninfoURL(){

        return API_URL+"v1/desc/tokeninfo/cn/android";

    }


    public static void setFlag(boolean isFlag) {
        APIModule.isFlag = isFlag;
    }

    public static void setFrontUrl(String url) {
        FRONT_URL = getUrl(url);
    }

    public static void setSessioneEror(boolean sessioneEror) {
        APIModule.sessioneEror = sessioneEror;
    }

    public static boolean isSessioneEror() {
        return sessioneEror;
    }

    public String getFileUrl() {
        return fileUrl;
    }

    public void setFileUrl(String fileUrl) {
        this.fileUrl = fileUrl;
    }


    private static APIModule instance = null;


    public static APIModule get() {
        synchronized (mLock) {
            if (instance == null) {
                instance = new APIModule();
            }
            return instance;
        }
    }

    public static void selectUrl(int select) {
        switch (select) {
            case 1:
                BASE_URL = BASE_TEST_TW5;
                break;
            case 2:
                BASE_URL = BASE_TEST_TW3;
                break;
            case 3:
                BASE_URL = BASE_TEST_TW1;
                break;
            case 4:
                BASE_URL = BASE_TEST_TW5;
                break;
        }

    }

    public void init() {

    }

    public static void setParameter(Map<String, String> parameter) {
        APIModule.mParameter = parameter;
    }


    private static Retrofit getRetrofit() {

        mRetrofit = new Retrofit.Builder()
                .baseUrl(BuildConfig.SERVERHEAD)
                .addConverterFactory(StringConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .client(getOkHttpClient())
                .build();
        return mRetrofit;

    }

    public static OkHttpClient getOkHttpClient() {
        mOkHttpClient = new OkHttpClient.Builder()
                .connectTimeout(HTTP_CONNECT_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(HTTP_WRITE_TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(HTTP_READ_TIMEOUT, TimeUnit.SECONDS)
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        if (s.endsWith("niren.org")||s.endsWith("tigerwallet.cn")){
                            LogUtils.a("OkHttpClien","::"+s);
                            return true;
                        }else {
                            return false;
                        }




                    }
                })
                .addInterceptor(new BasicParamsInterceptor())
                .build();
        return mOkHttpClient;

    }


    public static <T> T create(Class<T> zz) {

        return getRetrofit().create(zz);

    }


    public static class BasicParamsInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request newRequest = null;
            Request request = chain.request();
            //获取老的url
            HttpUrl oldUrl = request.url();
            //获取request的创建者builder
            Request.Builder builder = request.newBuilder();
            //获取头信息的集合如
            List<String> urlnameList = request.headers("urlname");
            if (urlnameList != null && urlnameList.size() > 0) {
                //删除原有配置中的值,就是namesAndValues集合里的值
                builder.removeHeader("urlname");
                //获取头信息中配置的value,如：manage或者mdffx
                String urlname = urlnameList.get(0);
                HttpUrl baseURL = null;
                //根据头信息中配置的value,来匹配新的base_url地址
                if ("init".equals(urlname)) {
                    baseURL = HttpUrl.parse(BuildConfig.SERVERHEAD);
                } else if ("login".equals(urlname)) {
                    baseURL = HttpUrl.parse(API_URL);
                } else {
                    baseURL = HttpUrl.parse(FRONT_URL);
                }
                //重建新的HttpUrl，需要重新设置的url部分
                HttpUrl newHttpUrl = oldUrl.newBuilder()
                        .scheme(baseURL.scheme())//http协议如：http或者https
                        .host(baseURL.host())//主机地址
                        .port(baseURL.port())//端口
                        .build();
                //获取处理后的新newRequest
                newRequest = builder.url(newHttpUrl).build();
            }

            if (null == newRequest) {
                newRequest = request;
            }


            if (isFlag){
                String session = mParameter.get("session");
                if (TextUtils.isEmpty(session)) {
//                    Log.e("BasicParamsInterceptor", ":11111111111111::" + session);
                    UserInfo.get().getNewSession();
                }
                if (sessioneEror){
//                    Log.e("BasicParamsInterceptor", ":22222222222222222::" + session);
                    UserInfo.get().getNewSession();
                }

            }



//            if (isFlag) {
//                String session = mParameter.get("session");
//                if (TextUtils.isEmpty(session)) {
////                    session = UserInfo.get().getNewSession();
//                    Log.e("BasicParamsInterceptor", ":session::" + session);
//                }
//                chain.proceed(request).close();
//
//            }

            if (newRequest.method().equals("GET")) {
                HttpUrl.Builder builder2 = newRequest.url().newBuilder();
                for (Map.Entry<String, String> entry : mParameter.entrySet()) {
                    builder2.addQueryParameter(entry.getKey(), entry.getValue());
                }
                HttpUrl httpUrl = builder2.build();
                request = newRequest.newBuilder().url(httpUrl).build();
            }
            if (newRequest.method().equals("POST")) {
                if (request.body() instanceof FormBody) {
                    FormBody.Builder bodyBuilder = new FormBody.Builder();
                    FormBody formBody = (FormBody) request.body();
                    //把原来的参数添加到新的构造器，（因为没找到直接添加，所以就new新的）
                    for (int i = 0; i < formBody.size(); i++) {
                        bodyBuilder.addEncoded(formBody.encodedName(i), formBody.encodedValue(i));
                    }
                    for (Map.Entry<String, String> entry : mParameter.entrySet()) {
                        bodyBuilder.addEncoded(entry.getKey(), entry.getValue());
                    }
                    formBody = bodyBuilder.build();
                    request = request.newBuilder().post(formBody).build();
                }
            }

            Log.e("Interceptor>>", "req:" + request.url());
            return chain.proceed(request);
        }
    }


    public static APIService getApi() {
        return create(APIService.class);

    }


}
